<template>
  <div class="form-container">
    <el-container>
      <el-main>
        <el-steps :active="1" align-center>
          <el-step title="步骤1" description="填写公司认证信息" />
          <el-step title="步骤2" description="签订入驻合同" />
          <el-step title="步骤3" description="公司申请入驻成功" />
        </el-steps>

        <el-form :model="ruleForm" ref="ruleFormRef" label-width="120px" class="custom-form" :rules="rules">
          <h1 class="form-title">填写公司认证信息</h1>

          <el-form-item label="公司名称" prop="name" required>
            <el-input v-model="ruleForm.name" />
          </el-form-item>

          <!-- 公司行业属性 -->
          <el-form-item label="行业属性" prop="industryType" required>
            <el-select v-model="ruleForm.industryType" placeholder="请选择行业属性" style="width: 100%">
              <el-option v-for="item in industryTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <!-- 新增的企业人数输入项 -->
          <el-form-item label="企业人数" prop="employeeCount" required>
            <el-input-number v-model="ruleForm.employeeCount" :min="1" :max="100000" :step="1" step-strictly
              placeholder="请输入企业人数" style="width: 100%" />
          </el-form-item>

          <el-form-item label="归属城市" prop="selectedArea" required>
            <el-cascader v-model="ruleForm.selectedArea" :options="areaOptions" :props="cascaderProps"
              placeholder="请选择省市区" clearable filterable />
          </el-form-item>

          <el-form-item label="详细地址" prop="address" required>
            <el-input type="textarea" v-model="ruleForm.address" class="address-textarea" :rows="3" />
          </el-form-item>

          <el-form-item label="社会信用码" prop="creditcode" required>
            <el-input v-model="ruleForm.creditcode" />
          </el-form-item>

          <el-form-item label="法人姓名" prop="legalpersonname" required>
            <el-input v-model="ruleForm.legalpersonname" />
          </el-form-item>

          <el-form-item label="法人手机号码" prop="legalpersonphone" required>
            <el-input v-model="ruleForm.legalpersonphone" />
          </el-form-item>

          <el-form-item label="法人身份证号" prop="legalpersonidcard" required>
            <el-input v-model="ruleForm.legalpersonidcard" />
          </el-form-item>

          <!-- 身份证上传区域 -->
          <el-form-item label="法人身份证" required>
            <div class="id-card-upload-group">
              <div class="id-card-upload-item">
                <div class="upload-sub-label">正面</div>
                <el-upload name="file_name" :action="uploadUrl" list-type="picture-card"
                  :file-list="ruleForm.idCardFrontList" :on-preview="handlePictureCardPreview"
                  :on-remove="() => handleRemove(2)" :before-upload="(file) => beforeUpload(file, 2)"
                  :on-success="(res) => handleSuccess(res, 2)" :on-error="handleUploadError" class="id-card-uploader"
                  accept=".jpg,.jpeg,.png">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
              <div class="id-card-upload-item">
                <div class="upload-sub-label">反面</div>
                <el-upload name="file_name" :action="uploadUrl" list-type="picture-card"
                  :file-list="ruleForm.idCardBackList" :on-preview="handlePictureCardPreview"
                  :on-remove="() => handleRemove(3)" :before-upload="(file) => beforeUpload(file, 3)"
                  :on-success="(res) => handleSuccess(res, 3)" :on-error="handleUploadError" class="id-card-uploader"
                  accept=".jpg,.jpeg,.png">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
            <div class="upload-tip">请上传JPG/PNG格式，大小不超过2MB</div>
          </el-form-item>


          <el-form-item label="营业执照" required>
            <el-upload name="file_name" class="license-upload" :action="uploadUrl" :file-list="ruleForm.licenseList"
              :on-preview="handlePictureCardPreview" :on-remove="() => handleRemove(1)"
              :before-upload="(file) => beforeUpload(file, 1)" :on-success="(res) => handleSuccess(res, 1)"
              :on-error="handleUploadError" multiple :limit="3" accept=".jpg,.jpeg,.png,.pdf">
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传JPG/PNG/PDF格式，每个文件不超过5MB</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item class="form-actions">
            
              <el-button type="primary" @click="handleSubmit">
                下一步
              </el-button>
            
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="previewVisible" title="文件预览" width="70%">
          <template v-if="previewUrl.endsWith('.pdf')">
            <embed :src="previewUrl" type="application/pdf" width="100%" height="600px"
              style="min-height: 500px; border: 1px solid #eee;">
          </template>
          <template v-else-if="isImageFile(previewUrl)">
            <img :src="previewUrl" style="max-width: 100%; display: block; margin: 0 auto;">
          </template>
          <template v-else>
            <div class="unsupported-preview">
              <el-icon :size="50">
                <Document />
              </el-icon>
              <p>不支持预览该文件类型</p>
              <a :href="previewUrl" target="_blank">下载文件</a>
            </div>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { regionData } from 'element-china-area-data'
import { Plus, Document } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'
import { Download } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router' // 添加useRouter导入

// 添加路由
const router = useRouter();

// 添加文件类型检测
const isImageFile = (url) => {
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url || '');
};

// 添加上传headers
const uploadHeaders = {
  'X-Requested-With': 'XMLHttpRequest',
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
};

// 后端API地址
// 从环境变量中获取基础地址，自动适配环境
const baseApiUrl = import.meta.env.VITE_API_BASE_URL;
const uploadUrl = `${baseApiUrl}/api/upload`;

// 表单引用
const ruleFormRef = ref(null)

// 表单数据
const ruleForm = reactive({
  name: '',
  industryType: '',
  employeeCount: 1, // 新增的企业人数字段，默认值为1
  selectedArea: [],
  creditcode: "",
  legalpersonname: "",
  legalpersonphone: "",
  legalpersonidcard: "",
  address: "",
  // 文件列表
  licenseList: [],    // 营业执照 (file_type=1)
  idCardFrontList: [], // 身份证正面 (file_type=2)
  idCardBackList: [],  // 身份证反面 (file_type=3)
  
})

// 预览相关
const previewUrl = ref('')
const previewVisible = ref(false)

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  industryType: [
    { required: true, message: '请选择行业属性', trigger: 'change' }
  ],
  employeeCount: [
    { required: true, message: '请输入企业人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '人数必须大于0', trigger: 'blur' }
  ],
  selectedArea: [
    { required: true, message: '请选择归属城市', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  creditcode: [
    { required: true, message: '请输入社会信用码', trigger: 'blur' },
    { min: 18, max: 18, message: '社会信用码长度为18位', trigger: 'blur' }
  ],
  legalpersonname: [
    { required: true, message: '请输入法人姓名', trigger: 'blur' }
  ],
  legalpersonphone: [
    { required: true, message: '请输入法人手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  legalpersonidcard: [
    { required: true, message: '请输入法人身份证号', trigger: 'blur' },
    { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
})

// 公司类型选项
const industryTypes = [
  { value: 1, label: '制造业' },
  { value: 2, label: '信息技术' },
  { value: 3, label: '金融业' },
  { value: 4, label: '教育培训' },
  { value: 5, label: '医疗健康' },
  { value: 6, label: '零售业' },
  { value: 7, label: '物流运输' },
  { value: 8, label: '建筑工程' },
  { value: 9, label: '餐饮服务' },
  { value: 10, label: '文化娱乐' },
  { value: 11, label: '房地产' },
  { value: 12, label: '能源环保' },
  { value: 13, label: '农业' },
  { value: 14, label: '旅游酒店' },
  { value: 15, label: '媒体广告' },
  { value: 16, label: '咨询服务' },
  { value: 17, label: '其他行业' }
]

// 地区选择配置
const areaOptions = regionData
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  expandTrigger: 'hover'
}

// 文件上传前校验
const beforeUpload = (file, fileType) => {
  // 通用文件大小限制
  const maxSize = fileType === 1 || fileType === 4 ? 5 : 2; // 营业执照和法人证书5MB，身份证2MB
  const isLtMaxSize = file.size / 1024 / 1024 < maxSize;

  if (!isLtMaxSize) {
    ElMessage.error(`文件大小不能超过${maxSize}MB!`);
    return false;
  }

  // 文件类型校验
  const isImage = file.type.startsWith('image/');
  const isPdf = file.type === 'application/pdf';

  // 身份证只允许图片
  if ((fileType === 2 || fileType === 3) && !isImage) {
    ElMessage.error('请上传图片文件!');
    return false;
  }

  // 营业执照和法人证书允许图片和PDF
  if ((fileType === 1 || fileType === 4) && !isImage && !isPdf) {
    ElMessage.error('请上传图片或PDF文件!');
    return false;
  }

  return true;
};

// 上传成功处理
const handleSuccess = (response, fileType) => {
  if (response.code !== 200) {
    ElMessage.error(response.msg || '上传失败');
    return;
  }

  const fileData = {
    name: response.data.fileName,
    url: response.data.fileUrl
  };

  // 根据文件类型添加到对应的列表
  switch (fileType) {
    case 1: // 营业执照
      ruleForm.licenseList.push(fileData);
      break;
    case 2: // 身份证正面
      ruleForm.idCardFrontList = [fileData];
      break;
    case 3: // 身份证反面
      ruleForm.idCardBackList = [fileData];
      break;
    
  }

  ElMessage.success('上传成功');
};

// 移除文件处理
const handleRemove = (fileType) => {
  switch (fileType) {
    case 1: // 营业执照
      ruleForm.licenseList = [];
      break;
    case 2: // 身份证正面
      ruleForm.idCardFrontList = [];
      break;
    case 3: // 身份证反面
      ruleForm.idCardBackList = [];
      break;
    
  }
};

// 上传失败处理
const handleUploadError = (err) => {
  ElMessage.error('文件上传失败，请重试');
  console.error('上传失败：', err);
};

// 预览处理
const handlePictureCardPreview = (file) => {
  previewUrl.value = file.response?.data?.fileUrl || file.url || (file.raw ? URL.createObjectURL(file.raw) : '');
  if (!previewUrl.value) {
    ElMessage.error('无法获取文件预览地址');
    return;
  }
  previewVisible.value = true;
};

// 表单提交处理
const handleSubmit = async (navigate) => {

  if (!ruleFormRef.value) return;

  try {
    await ruleFormRef.value.validate();

    // 验证文件上传
    if (ruleForm.idCardFrontList.length === 0) {
      ElMessage.warning('请上传身份证正面');
      return;
    }

    if (ruleForm.idCardBackList.length === 0) {
      ElMessage.warning('请上传身份证反面');
      return;
    }

   

    if (ruleForm.licenseList.length === 0) {
      ElMessage.warning('请上传营业执照');
      return;
    }

    // 构造提交数据
    const submitData = {
      name: ruleForm.name,
      type: ruleForm.industryType,
      personNumber: ruleForm.employeeCount, // 新增的企业人数字段
      region: ruleForm.selectedArea.join('/'),
      address: ruleForm.address,
      creditCode: ruleForm.creditcode,
      legalPersonName: ruleForm.legalpersonname,
      legalPersonPhone: ruleForm.legalpersonphone,
      legalPersonIdCard: ruleForm.legalpersonidcard,
      files: [
        // 营业执照
        ...ruleForm.licenseList.map(file => ({
          file_type: 1,
          file_url: file.url,
          file_name: file.name
        })),
        // 身份证正面
        ...ruleForm.idCardFrontList.map(file => ({
          file_type: 2,
          file_url: file.url,
          file_name: file.name
        })),
        // 身份证反面
        ...ruleForm.idCardBackList.map(file => ({
          file_type: 3,
          file_url: file.url,
          file_name: file.name
        }))
        
      ]
    };

    // 提交到后端
    const loading = ElLoading.service({ text: '提交中...' });
    const res = await axios.post(`${baseApiUrl}/api/companyregister`, submitData);

    if (res.data.code === 200) {
      ElMessage.success('公司信息保存成功，进入下一步');
      console.log('即将跳转，传递的参数：', {
        companyName: ruleForm.name,
        creditCode: ruleForm.creditcode
      });
      router.push({
        path: '/contract',
        query: {
          companyName: ruleForm.name,
          creditCode: ruleForm.creditcode
        }
      });
    } else {
      ElMessage.error(res.data.msg || '保存失败，请重试');
    }

    loading.close();
  } catch (error) {
    if (error.name !== 'Error') {
      // 表单验证失败
      return;
    }
    ElMessage.error('提交失败，请重试');
    console.error('提交错误：', error);
  }

};

// 重置表单
const resetForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }

  // 重置文件相关
  ruleForm.licenseList = [];
  ruleForm.idCardFrontList = [];
  ruleForm.idCardBackList = [];
  ruleForm.certificateList = [];

  // 重置企业人数为默认值1
  ruleForm.employeeCount = 1;
};
</script>

<style scoped>
.unsupported-preview {
  text-align: center;
  padding: 40px;
  color: #666;
}

.unsupported-preview a {
  color: #409eff;
  text-decoration: none;
  margin-top: 20px;
  display: inline-block;
}

.unsupported-preview a:hover {
  text-decoration: underline;
}

/* 图片预览优化 */
:deep(.el-dialog__body img) {
  max-height: 70vh;
  object-fit: contain;
}


.form-container {
  background-color: white;
  display: flex;
  justify-content: center;
  padding: 20px;
  min-height: 100vh;
  box-sizing: border-box;
}

.custom-form {
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

/* 输入框样式 */
:deep(.el-input),
:deep(.el-textarea__inner),
:deep(.el-cascader),
:deep(.el-input-number) {
  /* 新增的数字输入框样式 */
  width: 100%;
}

.address-textarea :deep(.el-textarea__inner) {
  min-height: 80px;
  resize: vertical;
}

/* 身份证上传区域 */
.id-card-upload-group {
  display: flex;
  gap: 30px;
  margin-top: 10px;
}

.id-card-upload-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-sub-label {
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

.upload-tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
  line-height: 1.5;
}

/* 上传卡片样式 */
:deep(.id-card-uploader .el-upload--picture-card) {
  width: 120px;
  height: 80px;
  line-height: 80px;
  border-radius: 4px;
}

:deep(.id-card-uploader .el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 80px;
  border-radius: 4px;
}

:deep(.certificate-uploader .el-upload--picture-card) {
  width: 160px;
  height: 120px;
  line-height: 120px;
  border-radius: 6px;
}

:deep(.certificate-uploader .el-upload-list--picture-card .el-upload-list__item) {
  width: 160px;
  height: 120px;
  border-radius: 6px;
}

/* 营业执照上传样式 */
.license-upload {
  width: 100%;
}

/* PDF预览样式 */
.pdf-preview {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.pdf-preview p {
  margin-top: 16px;
  word-break: break-all;
}

/* 按钮区域 */
.form-actions {
  margin-top: 40px;
  text-align: center;
}

.form-actions .el-button {
  width: 120px;
  margin: 0 10px;
}

/* 步骤条样式 */
:deep(.el-steps) {
  margin: 30px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-container {
    padding: 10px;
  }

  .custom-form {
    padding: 15px;
  }

  .id-card-upload-group {
    flex-direction: column;
    gap: 20px;
  }

  :deep(.el-form-item__label) {
    text-align: left;
  }

  :deep(.el-steps) {
    margin: 20px 0;
  }
}
</style>